<template>
    <el-card>
        <template #header>
            <span>密码管理</span>
        </template>
        <el-col :span="8">
            <el-form label-width="80px" :model="passForm" :rules="rules" ref="formIns">
                <el-form-item label="原始密码" prop="password">
                    <el-input v-model="passForm.password" type="password">
                    </el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newpassword">
                    <el-input v-model="passForm.newpassword" type="password">
                    </el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="repassword">
                    <el-input v-model="passForm.repassword" type="password">
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleChange">
                        确认修改
                    </el-button>
                </el-form-item>
            </el-form>
        </el-col>

    </el-card>

</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { FormRules, FormInstance } from "element-plus"
// 第一个是验证规则，一个是From实例
import { password } from '@/api/api';
import { ElMessage } from 'element-plus';
const passForm = reactive<PassForm>({
    id: sessionStorage.getItem("userid") as string,
    password: "",
    newpassword: "",
    repassword: "",
});
const passwordValidFn = (field: any, value: string, cb: any) => {
    let reg = /^[0-9a-zA-Z]{6,}$/;
    if (reg.test(value)) {
        cb()
    } else {
        cb(new Error("新密码必须是六位以上的数组或字母组成"))
    }
}

const repasswordValidFn = (field: any, value: string, cb: any) => {

    if (value != passForm.newpassword) {
        cb(new Error("保证两次输入一致"))
    } else {
        cb()
    }
}

const rules: FormRules = {
    password: { required: true, message: "请输入原始密码", trigger: "blur" },
    newpassword: [
        { required: true, message: "请输入新密码", trigger: "blur" },
        {
            validator: passwordValidFn, trigger: "blur"
        }],
    repassword: [
        { required: true, message: "请重新输入密码", trigger: "blur" },
        {
            validator: repasswordValidFn, trigger: "blur"
        }],
}

const formIns = ref<FormInstance>();
const handleChange = async () => {
    
    try {
        await formIns.value?.validate();
        const res = await password(passForm);
        if (res.data.code === 200) {
            
            
            ElMessage.success("修改成功");
            formIns.value?.resetFields();
        }else{
            ElMessage.error("修改失败");
        }
    } catch (e) {

    }
}
</script>
<style></style>